package com.company.Thread.DelayQueue;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayTask<T extends  Runnable> implements Delayed {
    // 任务延迟时间
    private final long time;
    // 任务类
    private final T task;

    public DelayTask(long timeout, T task) {
        this.time = System.nanoTime() + timeout;
        this.task = task;
    }


    @Override
    public int compareTo(Delayed o) {
        DelayTask<?> other = (DelayTask<?>) o;
        long diff = time - other.time;
        if (diff > 0) {
            return 1;
        } else if (diff < 0) {
            return -1;
        } else {
            return 0;
        }

    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.time - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    /**
     * 获取任务对象
     * @author zhangyan
     * @date 2020年2月20日 上午11:55:29
     * @return
     */
    public T getTask() {
        return task;
    }

}
